package com.fangdd.logtrace;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import java.util.concurrent.Callable;

/**
 * Set TraceId to thread local and MDC before calling callable, and clear them after.
 * Created by sulong on 16-9-6.
 */
public class TraceWith {
    private static final Logger LOGGER = LoggerFactory.getLogger(TraceWith.class);

    public static final String TRACE_ID_MDC_NAME = "fddTraceId";

    public static <V> V run(final TraceId traceId, Callable<V> callable) throws Exception {
        try {
            if (traceId != null) {
                TraceIdThreadLocal.set(traceId);

                MDC.put(TRACE_ID_MDC_NAME, traceId.toString());
            }

            return callable.call();
        } catch (Exception e) {
            LOGGER.debug("", e);
            throw e;
        } finally {
            TraceIdThreadLocal.clear();

            MDC.remove(TRACE_ID_MDC_NAME);
        }
    }
}
